import path from 'node:path';
import { config } from '@e/config';
import { ColorScheme } from '@p/utils';
import { errorDialog } from '@e/dialog';
import { __path } from '@e/methods/path';
import { getWindowList } from '@e/utils/global';
import { WindowService } from './WindowService';
import { bindWindowEvent } from './bindWindowEvent';
import { BrowserWindow, nativeTheme, screen } from 'electron';
import { CreateWindowConfig, WindowObject } from '@p/main-windowObject';

interface ColorInfo {
	backgroundColor: string;
	colorScheme: ColorScheme;
}

// createWindow 默认配置
const defaultConfig: CreateWindowConfig = {
	// 是否处于多开
	openMore: false,
};

// 获取颜色信息
function getColorInfo() {
	const obj: ColorInfo = {
		backgroundColor: '#1B1E2D',
		colorScheme: 'dark',
	};

	switch (config.configFile.base.defaultColorMode) {
		case 'follow-system':
			if (nativeTheme.shouldUseDarkColors) {
				obj.backgroundColor = '#1B1E2D';
				obj.colorScheme = 'dark';
			} else {
				obj.backgroundColor = '#f5f5f5';
				obj.colorScheme = 'light';
			}
			break;
		case 'dark':
			obj.backgroundColor = '#1B1E2D';
			obj.colorScheme = 'dark';
			break;
		case 'light':
			obj.backgroundColor = '#f5f5f5';
			obj.colorScheme = 'light';
			break;
	}

	return obj;
}

// 设置窗口位置
function setWindowPosition(s: boolean) {
	const { width: screenWidth, height: screenHeight } = screen.getPrimaryDisplay().workAreaSize;

	const windowList = getWindowList();

	let t_window;

	type Position = {
		x?: number;
		y?: number;
	};

	const obj: Position = {};

	if (s) {
		const item = windowList[windowList.length - 1];

		if (item) {
			const [x, y] = item.window.getPosition();

			t_window = item.window;

			obj.x = x + 40;
			obj.y = y + 40;
		}
	} else {
		for (let i = 0; i < windowList.length; i++) {
			const window = windowList[i].window;

			if (window.isFocused() && !window.isFullScreen() && !window.isMaximized()) {
				const [x, y] = windowList[i].window.getPosition();

				t_window = windowList[i].window;

				obj.x = x + 40;
				obj.y = y + 40;

				break;
			}
		}
	}

	if (t_window) {
		const [windowWidth, windowHeight] = t_window.getSize();

		if ((obj.x as number) + windowWidth > screenWidth) {
			obj.x = 10;
		}

		if ((obj.y as number) + windowHeight > screenHeight) {
			obj.y = 10;
		}
	}

	return obj;
}

// 获取预加载文件路径
function getPreloadPath() {
	if (config.isDevEnv()) {
		return path.join(__dirname, '../utils/preload.js');
	} else {
		return path.join(__dirname, './preload.js');
	}
}

/**
 * 创建窗口
 * @param _path
 * @param _config
 * @returns
 */
export function createWindow(_path?: string, _config?: CreateWindowConfig) {
	if (_path && !__path.check.isMdFilePath(_path)) {
		errorDialog('错误', `"${_path}" 不是一个正确的 markdown 文档路径`);
		_path = void 0;
	}

	_config = { ...defaultConfig, ..._config };

	const colorInfo = getColorInfo();

	const myOptions = {
		backgroundColor: colorInfo.backgroundColor,
		...setWindowPosition(_config.openMore),
	};

	const window = new BrowserWindow({
		width: config.windowDefaultSize.width,
		height: config.windowDefaultSize.height,
		show: false,
		// frame: false, // 无边框窗口
		autoHideMenuBar: true, // 不显示meun菜单
		webPreferences: {
			preload: getPreloadPath(),
			webSecurity: false,
		},
		...myOptions,
	});

	// 获取渲染进程id
	const id = window.webContents.id;

	if (config.isDevEnv()) {
		window.loadURL(config.getWindowloadValue());
	} else {
		window.loadFile(config.getWindowloadValue());
	}

	// 创建窗口服务对象
	const service = new WindowService(window, id, _path, {
		colorScheme: colorInfo.colorScheme,
	});

	const obj: WindowObject = {
		id,
		window,
		service,
	};

	// 给窗口绑定事件
	bindWindowEvent(obj);

	// 当窗口页面加载完毕才显示窗口
	obj.window.once('ready-to-show', () => {
		obj.window.show();
		obj.window.webContents.send('id', obj.id);
	});

	// 将窗口对象添加到 global.windowList 中
	// global.windowList.push(obj);
	getWindowList().push(obj);

	return obj;
}

/**
 * 批量创建窗口
 */
export function batchCreateWindow(paths?: string[]) {
	if (!paths) return;

	const s = paths.length > 1;
	let index = 0;

	const next = () => {
		if (index < paths.length) {
			const obj = createWindow(paths[index++], { openMore: s });

			if (s) {
				obj.service.on('load', next, true);
			}
		}
	};

	next();
}
